import React, { Component } from "react"

import logo from "../logo.svg"
import Ionicon from "react-ionicons"
import img1 from "../assets/img1.jpg"
import img2 from "../assets/img2.jpg"
import img3 from "../assets/img3.jpg"
import img4 from "../assets/img4.jpeg"

import PriceList from "../components/PriceList"
import TotalPrice from "../components/TotalPrice"
import MonthPicker from "../components/MonthPicker"
import CreateBtn from "../components/CreateBtn"
import Tabs, { Tab } from "../components/Tabs"
import Carousel, { CarouselItem } from "../components/Carousel"
import Loader from "../components/Loader"
import withContext from "../withContext"
import CustomPieChart from "../components/CustomPieChart"

import {
  VIEW_LIST,
  VIEW_CHART,
  TYPE_INCOME,
  parseToYearAndMonth,
  TYPE_EXPENSE
} from "../utility"

const tabsText = [VIEW_LIST, VIEW_CHART]

const generateChartDataByCategory = (items, type = TYPE_INCOME) => {
  let categoryMap = {}
  items
    .filter(item => item.category.type === type)
    .forEach(item => {
      if (categoryMap[item.cid]) {
        categoryMap[item.cid].value += item.price * 1
        categoryMap[item.cid].items.push(item.id)
      } else {
        categoryMap[item.cid] = {
          name: item.category.name,
          value: item.price * 1,
          items: [item.id]
        }
      }
    })
  return Object.keys(categoryMap).map(key => ({ ...categoryMap[key] }))
}

class Home extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selectedDate: parseToYearAndMonth("2018-12"),
      tabView: VIEW_LIST
    }
  }

  componentDidMount() {
    this.props.actions.getInitalData()
  }

  handleChangeView = index => {
    this.setState({
      tabView: tabsText[index]
    })
  }

  handleChangeDate = (year, month) => {
    this.setState({
      selectedDate: {
        month,
        year
      }
    })
    this.props.actions.selectNewDate(year, month)
  }

  handleModifyItem = modifiedItem => {
    this.props.history.push("/edit/" + modifiedItem.id)
  }

  handleCreateItem = () => {
    this.props.history.push("/create")
  }

  handleDeleteItem = deletedItem => {
    this.props.actions.deleteItem(deletedItem)
  }

  render() {
    const { data } = this.props
    const { items, categories, isLoading } = data
    const { selectedDate, tabView } = this.state
    // 为 items 中添加 category 值，并将其转换为数组
    const itemsWithCategory = Object.keys(items).map((key, index) => {
      // 注意这里的 item 是 items 中的对象，所以需要先进行拷贝，否则会将存放在 context 中的 items 中每个对象添加一个 category
      const copyItem = { ...items[key] }
      copyItem.category = categories[items[key].cid]
      return copyItem
    })

    const chartExpenseDataByCategory = generateChartDataByCategory(
      itemsWithCategory,
      TYPE_EXPENSE
    )

    const chartIncomeDataByCategory = generateChartDataByCategory(
      itemsWithCategory,
      TYPE_INCOME
    )

    // 收入和支出总金额的计算
    let totalIncome = 0,
      totalExpense = 0
    itemsWithCategory.forEach(item => {
      if (item.category.type === TYPE_INCOME) {
        totalIncome += item.price
      } else {
        totalExpense += item.price
      }
    })

    return (
      <React.Fragment>
        <header className="App-header align-items-stretch">
          <div className="row mb-5 justify-content-center">
            <img src={logo} className="App-logo" alt="logo" />
          </div>
          <div className="row">
            <div className="col">
              <MonthPicker
                year={selectedDate.year}
                month={selectedDate.month}
                onChangeDate={this.handleChangeDate}
              />
            </div>
            <div className="col row align-item s-center">
              <TotalPrice income={totalIncome} expense={totalExpense} />
            </div>
          </div>
        </header>
        <div className="home-content py-3 px-3">
          {isLoading && <Loader />}
          <Tabs
            activeIndex={tabsText.indexOf(tabView)}
            onTabChange={this.handleChangeView}
          >
            <Tab>
              <Ionicon
                className="rounded-circle"
                fontSize="30px"
                color="#007bff"
                icon="ios-paper"
              />
              列表模式
            </Tab>
            <Tab>
              <Ionicon
                className="rounded-circle"
                fontSize="30px"
                color="#007bff"
                icon="ios-pie"
              />
              图表模式
            </Tab>
          </Tabs>
          <CreateBtn
            onCreateItem={this.handleCreateItem}
            test="创建一条新的记账记录"
          />
          {tabView === VIEW_LIST && (
            <PriceList
              items={itemsWithCategory}
              onModifyItem={this.handleModifyItem}
              onDeleteItem={this.handleDeleteItem}
            />
          )}
          {tabView === VIEW_CHART && (
            <div className="chart-container d-flex">
              <div className="flex-fill">
                <CustomPieChart
                  title="本月支出"
                  categoryData={chartExpenseDataByCategory}
                />
              </div>
              <div className="flex-fill">
                <CustomPieChart
                  title="本月收入"
                  categoryData={chartIncomeDataByCategory}
                />
              </div>
            </div>
          )}
        </div>
        <div className="mt-5" />
        <Carousel>
          <CarouselItem>
            <div className="img-wrapper">
              <img src={img1} alt="" />
            </div>
          </CarouselItem>
          <CarouselItem>
            <div className="img-wrapper">
              <img src={img2} alt="" />
            </div>
          </CarouselItem>
          <CarouselItem>
            <div className="img-wrapper">
              <img src={img3} alt="" />
            </div>
          </CarouselItem>
          <CarouselItem>
            <div className="img-wrapper">
              <img src={img4} alt="" />
            </div>
          </CarouselItem>
        </Carousel>
      </React.Fragment>
    )
  }
}

export default withContext(Home)
